<template>
  <div class="mask">
    <div class="sign-canvas">
      <canvas ref="canvas" @mousemove="canvasMove" @mouseup="canvasUp" width="800" height="300" @mousedown="mousedown" @mouseleave="canvasLeave"></canvas>
      <div class="btn-list">
        <div class="btn-left">
          <el-button type="primary" @click="handleClear" size="large">重 置</el-button>
          <el-button type="primary" @click="handlePrev" size="large">上一步</el-button>
        </div>
        <el-button type="primary" @click="handleSave" size="large">保 存</el-button>

      </div>
    </div>

  </div>
</template>
<script setup>
import { ref } from 'vue'
const emits = defineEmits(['handleSave', 'handlePrev'])
const visible = ref(true)
const isDown = ref(false) // 是否可以绘制
const canvas = ref(null) // canvas 元素
const ctx = ref(null) // ctx承接上下文

// 鼠标按下
function mousedown (e) {
  let { offsetX, offsetY } = e // 拿到x，y坐标
  ctx.value = canvas.value.getContext('2d') // 上下文
//   console.log(ctx.value)
  ctx.value.strokeStyle = '#000'; // 设置线条颜色
  ctx.value.fillStyle = '#fff'
  ctx.value.lineWidth = 5; // 线条宽度
  ctx.value.beginPath(); // 开始绘制路径
  ctx.value.moveTo(offsetX, offsetY); // 将鼠标移动到某一个坐标，准备绘制
  isDown.value = true // 打开绘制开关
}
// 鼠标移动
function canvasMove (e) {
  let { offsetX, offsetY } = e // 拿到移动时的坐标信息
  isDown.value && startDraw(offsetX, offsetY) // 绘制开关为true 开始绘制
}
// 鼠标松开
function canvasUp() {
  console.log('松开');
  isDown.value = false
}
// 鼠标超出canvas绘制区域
function canvasLeave() {
  console.log('超出canvas');
  isDown.value = false
}
// 绘制方法
function startDraw(x, y) {
  ctx.value.lineTo(x, y); // 绘制线条
  ctx.value.stroke(); //
}
function handleClear() {
  ctx.value.clearRect(0, 0, 1000, 500)
}
const handlePrev = () => {
  emits('handlePrev')
}
function handleSave() {
  const base64 = canvas.value.toDataURL()
  emits('handleSave', base64)
  // console.log(base64) // 输出base64的图片地址
}
</script>
<style scoped>
:deep(.el-button--primary) {
  color: #fff;
  background-color: var(--color-main);
  border-color: var(--color-main)
}
.mask{
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 99;
}
.sign-canvas{
  width: 64vw;
  min-height: 300px;
  max-height: 90%;
  overflow: hidden;
  overflow-y: scroll;
  position: absolute;
  top: 50%;
  left: 50%;
  background: #fff;
  border-radius: 12px;
  transform: translate(-50%, -50%);
  padding: 1.25rem;
}
.btn-list{
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: .625rem 0;
  border-top: 1px solid #eee;
}
</style>